package com.tutorial.demo.download.controller;

import ch.qos.logback.core.util.FileUtil;
import com.tutorial.demo.download.pojo.TreeNodeDto;
import com.tutorial.demo.download.service.DownloadService;
import org.apache.tomcat.util.digester.DocumentProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.activation.MimetypesFileTypeMap;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;

@Controller
public class DownloadController {
    @Autowired
    private DownloadService downloadService;

    //找到对应页面
    @RequestMapping("/download")
    public String toPage(){
        return "/download";
    }

    //找到对应页面
    @RequestMapping("/download1")
    public String toPage1(){
        return "/download1";
    }

    @RequestMapping("/file/list")
    @ResponseBody
    public List<TreeNodeDto>  listFiles(){
        int parantId = 0;
        return downloadService.findAllByParentId(parantId);
    }

    @RequestMapping("/fileDownload")
    @ResponseBody
    public void fileDownload(@RequestParam String fileName) throws IOException {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletResponse response = requestAttributes.getResponse();
        // 设置信息给客户端不解析
//        String type = new MimetypesFileTypeMap().getContentType(fileName);
        // 设置contenttype，即告诉客户端所发送的数据属于什么类型
//        response.setHeader("Content-type",type);
        // 设置编码
//        String hehe = URLEncoder.encode(fileName, "utf-8");
        // 设置扩展头，当Content-Type 的类型为要下载的类型时 , 这个信息头会告诉浏览器这个文件的名字和类型。
//        response.setHeader("Content-Disposition", "attachment;filename=" + hehe);
//        FileUtil.download(fileName, response);
        downloadService.download(fileName,response);
    }

//    public static void main(String[] args) {
//        String fileName="上传和下载.doc";
//        String fileType = fileName.substring(fileName.lastIndexOf(".")+1);
//        System.out.println(fileType);
//    }

}
